package pers.cz.analysis.admin;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import pers.cz.analysis.entitys.ClassDesc;
import pers.cz.analysis.handle.ClassVisitor;
import pers.cz.analysis.utils.FileUtils;
import pers.cz.grammar.antlr.java.Java8Lexer;
import pers.cz.grammar.antlr.java.Java8Parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: Jef-code-analysis
 * @description: 分析者启动
 * @author: Cheng Zhi
 * @create: 2023-10-11 17:45
 **/
public class AnalysisStartor {

    private List<ClassDesc> classDescs = new ArrayList<ClassDesc>();

    public List<ClassDesc> getClassDescs() {
        return classDescs;
    }

    /**
     * 开始解析
     * @param filePath
     * @throws IOException
     */
    public void start(String filePath) throws IOException {
        List<String> files = FileUtils.readFile(filePath, ".java");
        files.forEach(fileName->{
            classDescs.addAll(process(fileName));
        });
    }

    /**
     *  解析并获取结果
     * @param fileName
     */
    private List<ClassDesc> process(String fileName) {
        CharStream inputStream = null;
        try {
            inputStream = CharStreams.fromFileName(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Java8Parser parser = new Java8Parser(new CommonTokenStream(new Java8Lexer(inputStream)));
        ParseTree parseTree = parser.compilationUnit();
        ClassVisitor classVisitor = new ClassVisitor();
        classVisitor.visit(parseTree);
        return  classVisitor.getClassDescs();
    }
}
